<script setup lang="tsx">
import { ref, useAttrs } from 'vue'
import { ElButton, ElInput, ElMessage } from 'element-plus'
import { Dialog } from '../../Dialog'
import Cron from './Cron.vue'

const slots = defineSlots<{
  prefix?: () => any
  suffix?: () => any
  prepend?: () => any
  append?: () => any
}>()

const attrs = useAttrs()

const modelValue = defineModel<string>('modelValue')

const dialogVisible = ref(false)

const cronRef = ref<InstanceType<typeof Cron>>()

const cronText = ref(modelValue.value)

function save() {
  cronRef.value?.validate().then(
    (res) => {
      modelValue.value = res
      dialogVisible.value = false
    },
    (e) => {
      ElMessage.warning(e)
    },
  )
}
</script>

<template>
  <ElInput v-bind="attrs" v-model="modelValue">
    <template v-if="slots.prefix" #prefix>
      <slot name="prefix" />
    </template>
    <template v-if="slots.suffix" #suffix>
      <slot name="suffix" />
    </template>
    <template v-if="slots.prepend" #prepend>
      <slot name="prepend" />
    </template>
    <template #append>
      <i
        class="uis:schedule h-14px w-14px cursor-pointer"
        @click="dialogVisible = true"
      />
      <Dialog v-model="dialogVisible" append-to-body title="Cron GUI选择器">
        <Cron ref="cronRef" v-model="cronText" />
        <template #footer>
          <ElButton type="primary" @click="save">
            保存
          </ElButton>
          <ElButton @click="dialogVisible = false">
            关闭
          </ElButton>
        </template>
      </Dialog>
      <slot name="append" />
    </template>
  </ElInput>
</template>

<style lang="less" scoped></style>
